const express = require('express')
const app = express()
const http = require('http');
const expressJWT = require('express-jwt')
const visitor = require('./router/visitor')
const user = require('./router/user')
const chat = require('./chat/chat')
let server = http.createServer(app);
const setting = require('./setting')
let io = chat.getSocket(server)
const cors = require('cors')

app.use(cors())

app.use('/public', express.static('public'));
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
//设置路由中间件
app.use(expressJWT({ secret: setting.mySecret, algorithms: ['HS256'] }).unless({ path: [/^\/api\//, /^\/public\//] }))
app.use('/user', user)
app.use('/api', visitor)

//错误中间件
app.use(function (err, req, res, next) {
    // 捕获身份认证失败的错误
    if (err.name === 'UnauthorizedError') {
        return res.send({
            status: 1,
            mes: '身份认证错误'
        })
    }
    if (err) return res.send({
        status: 1,
        mes: err
    })
    res.send({
        status: 1,
        mes: '服务器错误'
    })
})


server.listen('6060', () => {
    console.log('服务器已启动')
})